package _06模拟网站服务器;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class WebServer {
    public static void main(String[] args) throws IOException {
        System.out.println("服务器启动");
        //创建服务端
        ServerSocket ss = new ServerSocket(22222);

        while (true) {
            //获取浏览器的连接
            Socket socket = ss.accept();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //读取来自浏览器的数据
                        InputStream is = socket.getInputStream();
                        byte[] buf = new byte[1024];
                        int len = is.read(buf);
                        System.out.println(new String(buf, 0, len));

                        //将服务器的index.html页面返回给浏览器
                        //读取index.html文件，写出给浏览器（TCP客户端）
                        FileInputStream fis = new FileInputStream("day12\\web\\index.html");

                        OutputStream out = socket.getOutputStream();

                        //Http协议的固定格式
                        out.write("HTTP/1.1 200 OK\r\n".getBytes());
                        out.write("Content-Type:text/html\r\n".getBytes());
                        out.write("\r\n".getBytes());

                        while ((len = fis.read(buf)) != -1) {
                            out.write(buf, 0, len);
                        }

                        out.close();
                        fis.close();
                        is.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}